﻿using System;
using System.ComponentModel.Composition.Hosting;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Windows;
using System.Windows.Markup;
using System.Windows.Threading;
using Mari.SmartHotel.Controls;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Services.Clab.UI.Mvvmc;
using Microsoft.Services.Clab.UI.Mvvmc.Composition;

namespace Mari.SmartHotel.Shell
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        private Mutex applicationMutext;

        public IController ShellController { get; private set; }

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Application.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;

            if (!this.TryCreateMutex())
            {
                Application.Current.Shutdown();
                return;
            }

            this.SetLanguage("it-IT");

            this.InitializeMvvmc();

            ServiceLocator.Current.GetInstance<IControllerFactory>().CreateController(
                "Shell",
                onCreatedAction: c => this.ShellController = c,
                onInitializedAction: c =>
                {
                    this.MainWindow = c.ViewModel.Views.MainView as Window;
                    this.MainWindow.Show();
                    //CodeControllerBase.DefaultExceptionHandler = ex => { ShowFailureDlgAsync(ex); return true; };
                    //ControllerFactoryBase.DefaultExceptionHandler = ex => ShowFailureDlgAsync(ex);
                });
        }

        private bool TryCreateMutex()
        {
            string mutexName = Assembly.GetEntryAssembly().GetName().Name;
            bool mutexIsNew;

            applicationMutext = new Mutex(true, mutexName, out mutexIsNew);

            return mutexIsNew;
        }

        private void SetLanguage(string language)
        {
            Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo(language);
            Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
            FrameworkElement.LanguageProperty.OverrideMetadata(typeof(FrameworkElement), new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
        }

        private void InitializeMvvmc()
        {
            DispatcherProxy.Dispatcher = Application.Current.Dispatcher;
            MefServiceLocator.Initialize(new DirectoryCatalog(AppDomain.CurrentDomain.BaseDirectory, "Mari.SmartHotel.*"));
        }

        private void Current_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            //LoggingHelper.WriteTraceEntry(LoggingHelper.METHOD_ENTRY);

            if (e.Dispatcher == this.Dispatcher)
            {
                //if (applicationMutext != null)
                //{
                //    applicationMutext.ReleaseMutex();
                //}

                //LoggingHelper.WriteLogEntry(e.Exception.ToString(), TraceEventType.Error);
                //if (this.UpdateStatus == UpdateStatus.ApplicationNeedsToRestart)
                //{
                //    SHMessageBox.Show(Shell.Properties.Resources.UnhandledExceptionApplicationNeddRestart, Shell.Properties.Resources.DefaultHotelName, MessageBoxButton.OK, e.Exception);
                //}
                //else
                //{
                SHMessageBox.Show(Shell.Properties.Resources.UnhandledException, Shell.Properties.Resources.DefaultHotelName, MessageBoxButton.OK, e.Exception);
                //}
                e.Handled = true;
            }

            //LoggingHelper.WriteTraceEntry(LoggingHelper.METHOD_EXIT);
        }
    }
}
